<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import CustomNavbar from '@/pages/index/components/CustomNavbar.vue'
import { getHomeBannerAPI, getHomeHotAPI } from '@/services/home'
import { ref } from 'vue'
import type { BannerItem, HotItem } from '@/types/home'
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue'
import HotPanel from '@/pages/index/components/HotPanel.vue'
import XtxGuess from '@/components/XtxGuess.vue'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'
// 这里使用了uni-app 提供的组件自动导入
// import XtxSwiper from '@/components/XtxSwiper.vue'

// 自定义轮播图
const bannerList = ref<BannerItem[]>([])
// 是否正在加载中 是否显示骨架屏
const isLoading = ref(false)
/**
 * 获取首页轮播图数据
 */
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
// 热门推荐
const hotList = ref<HotItem[]>([])
/**
 * 获取首页热门数据
 */
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
// 获取猜你喜欢组件的实例对象
const guessRef = ref<XtxGuessInstance>()
// 滚动到底部时触发
const onScrolltolower = () => {
  guessRef.value?.getMore()
}
// 是否触发刷新页面
const isTriggered = ref(false)
// 下拉刷新
const onRefresherrefresh = async () => {
  isTriggered.value = true
  // await getHomeBannerData()
  // await getHomeHotData()
  // 重置数据
  guessRef.value?.resetData()
  await Promise.all([getHomeBannerData(), getHomeHotData(), guessRef.value?.getMore()])
  isTriggered.value = false
}
// 页面加载时
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeHotData()])
  isLoading.value = false
})
</script>

<template>
  <!--  自定义导航栏-->
  <CustomNavbar />
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrolltolower"
    scroll-y
    class="scroll-view"
  >
    <!--    骨架屏-->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!--  自定义轮播图-->
      <XtxSwiper :list="bannerList" />
      <!--  分类面板-->
      <CategoryPanel />
      <!--  热门推荐-->
      <HotPanel :list="hotList" />
      <!--  猜你喜欢-->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
